import React from "react";
import history from "@store//history";

type ErrorBoundaryProps = {
  children: any;
};
type ErrorBoundaryState = {
  hasError: boolean;
};

export default class ErrorBoundary extends React.PureComponent<ErrorBoundaryProps, ErrorBoundaryState> {
  constructor(props) {
    super(props);
    this.state = {
      hasError: false,
    };
  }

  static getDerivedStateFromError(error) {
    // 更新 state 使下一次渲染能够显示降级后的 UI
    console.log("getDerivedStateFromError", error);
    if (error.indexOf("React.lazy") > -1) {
      history.replace("/error");
      return { hasError: true };
    }
    return { hasError: false };
  }

  componentDidCatch(error, errorInfo) {
    // 你同样可以将错误日志上报给服务器
    // logErrorToMyService(error, errorInfo);
    console.log(this.props);
    console.log("componentDidCatch", error, errorInfo);
  }

  render() {
    const { hasError } = this.state;
    if (hasError) {
      // 你可以自定义降级后的 UI 并渲染
      return null;
    }
    const { children } = this.props;
    return children;
  }
}
